<?php

class MediaController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='application.modules.admin.views.layouts.default';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','create2','catelist','folder','update','category'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	public function actionCreate2()
	{
		var_dump($_REQUEST);
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Product;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);		

		if(isset($_POST['Product']))
		{
			$model->attributes=$_POST['Product'];
						
			if($model->save()){
//				$this->redirect(array('view','id'=>$model->pro_id));
				echo $this->createUrl('update', array('id'=>$model->pro_id));
				Yii::app()->end();
			}
		}
		
		$dataProvider=new CActiveDataProvider('Product');

		$this->render('create',array(
			'model'=>$model,
			'dataProvider'=>$dataProvider
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Product']))
		{
//			UtilTools::dump($_POST);
			$model->attributes=$_POST['Product'];
//			UtilTools::dump($model->attributes);
//			die();
			if($model->save())
				die('ok');
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	public function actionFolder($id)
	{
		
		$model = $this->loadModel($id);
		if(isset($_GET['fid']))
		{
			$model->pro_pic_id = $_GET['fid'];
			if($model->save())
				echo "ok";			
		}

	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		
//		$catelist = new CActiveDataProvider('Category',array(
//		     'criteria'=>array(
//		          'condition'=>'cate_type = '.Category::CATEGORY_PRODUCT,
//		          'order'=>'cate_id ASC ,cate_pid DESC',
//		          'with'=>array('product'),
//		     ),
//		      'pagination'=>array(
//		          'pageSize'=>5,
//		      ),
//		));
		
		$catelist = Category::model()->findAll(array(
		          'condition'=>'cate_type = '.Category::CATEGORY_PRODUCT,
		          'order'=>'cate_id ASC ,cate_pid DESC',
		          'with'=>array('product'),
		 ));
		 
		 $catelist = Category::model()->getChildrenObject($catelist);
		   
		
		$dataProvider=new CActiveDataProvider('Product');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
			'catelist'=>$catelist
		));
	}
	
    public function actionCategory()
    {

        $criteria = new CDbCriteria(
            array(
                'condition'=>'cate_type=:cate_type',
                'order'=>'cate_type ASC,cate_pid ASC,cate_order DESC',
                'params'=>array(
                    ':cate_type'=>Category::CATEGORY_PRODUCT
                )
            )
        );

		$dataProvider=new CActiveDataProvider('Category',array(
            'criteria'=>$criteria
        ));
	
		$model=new Category;

		// Uncomment the following line if AJAX validation is needed
 		$this->performAjaxValidation($model);
		

 		if(isset($_POST['Category']))
		{
			$count = Category::model()->count('cate_name = :cate_name',array(':cate_name'=>$_POST['Category']['cate_name']));
            
            if($count > 0)
            {
                die("exists");
            }
            
            $model->attributes=$_POST['Category'];    

//            var_dump($model->attributes);
//            die();
		
//            try {
//            	$model->save();
//            }
//            catch (CException $e)
//            {
//            	$e->getMessage();
//            }
			if($model->save()){
				die("ok");
			}else{
				die("fail");
			}
			
		}

		$this->render('category',array(
			'model'=>$model,
			'dataProvider'=>$dataProvider
		));
    }
	
	public function actionCateList()
	{
		$this->blackLayout();
		$criteria = new CDbCriteria(array(
			'condition'=>'cate_type = '.Category::CATEGORY_PRODUCT,
//			'limit'=>10,
//			'offset'=>10*($_GET['page']-1),
		));
		$count = Category::model()->count($criteria);
		
		$pages = new CPagination($count);
		$pages->pageSize = 5;
		$pages->applyLimit($criteria);
		
		$posts = Category::model()->findAll($criteria);
		$posts = Category::model()->getChildrenObject($posts);
		
		$this->render('catelist',array(
			'pages'=>$pages,
			'posts'=>$posts
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Product('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Product']))
			$model->attributes=$_GET['Product'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Product::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='product-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	protected function blackLayout()
	{
		return $this->layout='application.modules.admin.views.layouts.blank';
	}
	
	protected function baseLayout()
	{
		return $this->layout='application.modules.admin.views.layouts.base';
	}
}
